package com.whfp.coky

import android.app.Activity
import android.app.Application
import android.content.Context
import android.net.ConnectivityManager
import android.net.Network
import android.os.Build
import androidx.core.content.ContextCompat
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import com.hjq.bar.TitleBar
import com.hjq.toast.ToastUtils
import com.raizlabs.android.dbflow.config.DatabaseConfig
import com.raizlabs.android.dbflow.config.FlowConfig
import com.raizlabs.android.dbflow.config.FlowManager
import com.scwang.smart.refresh.footer.ClassicsFooter
import com.scwang.smart.refresh.header.MaterialHeader
import com.scwang.smart.refresh.layout.SmartRefreshLayout
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.constant.SpinnerStyle
import com.tencent.bugly.Bugly
import com.tencent.mmkv.MMKV
import com.whfp.afs330h_sdk.zx
import com.whfp.coky.db.dbflow.AppDatabase
import com.whfp.coky.db.dbflow.MyFlowSQliteOpenHelper
import com.whfp.coky.event.Event
import com.whfp.coky.event.EventMessage
import com.whfp.coky.manager.ActivityManager
import com.whfp.coky.other.TitleBarStyle
import com.whfp.coky.other.ToastStyle
import com.whfp.coky.utils.LogUtil


class App : Application() {

    companion object {
        var DEBUG: Boolean = false
        lateinit var instance: App

        fun post(eventMessage: EventMessage) {
            Event.getInstance().post(eventMessage)
        }
    }

    override fun onCreate() {
        super.onCreate()
        instance = this
        DEBUG = true
        initSdk(instance)
    }

    override fun onLowMemory() {
        super.onLowMemory()

    }

    private fun initSdk(application: Application) {

        //初始化数据库
        initDb()

        //初始化蓝牙
        zx.init(this)

        Bugly.init(application, "id", DEBUG)

        // Activity 栈管理初始化
        ActivityManager.getInstance().init(application)

        // MMKV 初始化
        MMKV.initialize(application)

        // 初始化吐司
        ToastUtils.init(application, ToastStyle());

        // 设置标题栏初始化器
        TitleBar.setDefaultStyle(TitleBarStyle())

        // 注册网络状态变化监听
        netListenerRegister(application)

//        db
//        val db = Room.databaseBuilder(
//            applicationContext,
//            ThresholdDB::class.java,
//            ""
//            )
    }

    private fun initDb() {
        /**
         * 初始化数据库
         */
        LogUtil.e("DatabaseConfigXXXXXXXXXXXXXXXXXX")



//        FlowManager.init(FlowConfig.Builder(this).build())
        FlowManager.init(
            FlowConfig.Builder(this)
                .addDatabaseConfig(
                    DatabaseConfig.builder(AppDatabase::class.java)
                        .openHelper(DatabaseConfig.OpenHelperCreator { databaseDefinition, helperListener ->
                            MyFlowSQliteOpenHelper(
                                databaseDefinition,
                                helperListener
                            )
                        })
                        .build()
                )
                .build()
        )

        LogUtil.e("DatabaseConfig${FlowManager.getConfig().getConfigForDatabase(AppDatabase::class.java)?.helperCreator()}")
    }

    override fun onTerminate() {
        super.onTerminate()
        FlowManager.destroy()
    }

    private fun netListenerRegister(application: Application) {
        // 注册网络状态变化监听
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M){
            ContextCompat.getSystemService(
                application,ConnectivityManager::class.java)?.let {
                    it.registerDefaultNetworkCallback(object : ConnectivityManager.NetworkCallback(){
                        override fun onLost(network: Network) {
                            val topActivity: Activity? = ActivityManager.getInstance().getTopActivity()
                            if (topActivity !is LifecycleOwner) {
                                return
                            }
                            val lifecycleOwner: LifecycleOwner = topActivity
                            if (lifecycleOwner.lifecycle.currentState != Lifecycle.State.RESUMED) {
                                return
                            }
                            ToastUtils.show(R.string.common_network_error)
                        }
                    })
            }
        }
    }

    init {
        //设置全局默认配置（优先级最低，会被其他设置覆盖）
        SmartRefreshLayout.setDefaultRefreshInitializer { _: Context?, layout: RefreshLayout ->
            //开始设置全局的基本参数
            layout.setFooterHeight(40f)
            layout.setDisableContentWhenLoading(false)
            layout.setDisableContentWhenRefresh(true) //是否在刷新的时候禁止列表的操作
            layout.setDisableContentWhenLoading(true) //是否在加载的时候禁止列表的操作
            layout.setEnableOverScrollBounce(false)
        }
        SmartRefreshLayout.setDefaultRefreshHeaderCreator { context: Context?, layout: RefreshLayout? ->
                MaterialHeader(context)
//            ClassicsHeader(context)
//                .setSpinnerStyle(SpinnerStyle.Translate)
//                .setTextSizeTitle(13f)
//                .setDrawableArrowSize(15f)
//                .setDrawableProgressSize(15f)
//                .setDrawableMarginRight(10f)
//                .setFinishDuration(0)
        }
        SmartRefreshLayout.setDefaultRefreshFooterCreator { context: Context?, layout: RefreshLayout? ->
            ClassicsFooter(context)
                .setSpinnerStyle(SpinnerStyle.Translate)
                .setTextSizeTitle(13f)
                .setDrawableArrowSize(15f)
                .setDrawableProgressSize(15f)
                .setDrawableMarginRight(10f)
                .setFinishDuration(0)
        }
    }


}